import { useRequest } from 'ahooks';
import { isEmptyObj } from '@/utils/util';
import { setStorage, getStorage } from '@/utils/storage';
import { dictValueTypes, dictTypeTypes } from '@/constants/types';
import { fetchAllDictOptions } from '@/pages/BasicInfo/services';
import { useCallback, useState } from 'react';
import configDict from "@/constants/dictData";

// 字典类型数组转换为对象格式
const composeDictData = (list: Array<dictTypeTypes>) => {
  const obj: any = {};
  list.forEach(item => {
    obj[item.dictType] = item.dictValues || [];
  })
  return obj;
}
/**
* 获取系统所有字典配置
* isRefresh 是否是刷新字典，为true时会重新从接口获取字典，否则从本地缓存获取
*/
const fetchDictApi = async (isRefresh = false) => {
  const localDict = getStorage('allDicts');
  if (!isEmptyObj(localDict) && !isRefresh) {
    return localDict;
  }
  const res = await fetchAllDictOptions();
  if (res && Array.isArray(res)) {
    const dicts = composeDictData(res);
    setStorage('allDicts', dicts);
    return dicts;
  }
  return {};
}

export default function Page() {
  const { data: allDicts, runAsync: fetchALLDicts, loading: loading } = useRequest(fetchDictApi, {manual: true});

  /**
   * 
   * @returns 刷新字典数据
   */
  const refreshDict = () => {
    if (loading) {
      return ;
    }
    // 刷新字典
    fetchALLDicts(true);
  }

  /**
   * 根据字典类型，及字典值的key获取字典值的label
   * type 字典的类型
   * key 字典值的key
   */
  const getDictLabel = useCallback((type: string, key: string | number | undefined) => {
    if (!type || (!key && key !== 0)) {
      return '';
    }
    if (!allDicts?.[type]?.length) {
      if (!configDict?.[type]?.length) {
        return '';
      }
      const curr = configDict?.[type].find((v: {label: string, value: string | number}) => {
        if (!/^\d+$/.test(String(key))) {
          return v.value === key
        }
        return +v.value === +key;
      });
      return curr?.label || '';
    }
    const curr = allDicts[type].find((v: dictValueTypes) => {
      if (!/^\d+$/.test(String(key))) {
        return v.dictValue === key
      }
      return +v.dictValue === +key;
    });
    return curr?.dictLabel || '';
  }, [JSON.stringify(allDicts)]);

  /**
   * 根据字典类型获取字典值数组，此方法为同步
   * type 字典类型key
   */
  const getDict = useCallback((type: string) => {
    if (!type) {
      return [];
    }
    if (!allDicts?.[type]?.length) {
      return [];
    }
    return allDicts?.[type]?.map((v: dictValueTypes) => ({
      ...v,
      label: v?.dictLabel,
      value: v?.dictValue
    }));
  }, [JSON.stringify(allDicts)]);

  /**
   * 根据字典类型获取字典值数组，此方法为异步
   * type 字典类型key
   */
  const getDictAsync = async (type: string) => {
    if (!type) {
      return [];
    }
    if (allDicts?.[type]?.length > 0) {
      return allDicts?.[type]?.map((v: dictValueTypes) => ({
        ...v,
        label: v?.dictLabel,
        value: v?.dictValue
      }));
    }
    const list = await fetchALLDicts();
    if (isEmptyObj(list)){
      return [];
    }
    return list?.[type]?.map((v: dictValueTypes) => ({
      ...v,
      label: v?.dictLabel,
      value: v?.dictValue
    }));
    
  }

 
  return {
    refreshDict,
    getDictLabel,
    getDict,
    getDictAsync,
    allDicts,
    loading,
  };
};